<template>
	<div style="width: 100%;">
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item><i class="el-icon-date"></i> 表单</el-breadcrumb-item>
				<el-breadcrumb-item>编辑器</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div style="height: 15px;">

		</div>

		<div style="width: 100%;">
			<editor :id='randomId' v-model='child_defaultValue' :init='init'></editor>
		</div>

	</div>

</template>
<script>
	import Common from './js/Common';
	import tinymce from 'tinymce/tinymce'
	import 'tinymce/themes/mobile/theme'
	import 'tinymce/themes/silver/theme'
	import Editor from "@tinymce/tinymce-vue";
	import 'tinymce/plugins/image'
	import 'tinymce/plugins/media'
	import 'tinymce/plugins/link'
	import 'tinymce/plugins/image'
	import 'tinymce/plugins/code'
	import 'tinymce/plugins/table'
	import 'tinymce/plugins/lists'
	import 'tinymce/plugins/wordcount'
	import 'tinymce/plugins/colorpicker'
	import 'tinymce/plugins/textcolor'
	import 'tinymce/plugins/contextmenu'
	import store from 'store/'
	import uploadPlugin from '../../utils/upload.js'
	import {
		gbs
	} from 'config/'
	import '../../../static/tinymce/axupimgs'

	export default {
    name: 'tinymce-editor',
    mixins:[Common],
		data() {
			return {
				tinymceHTML: 'hello world',
				init: {
					language_url: 'static/zh_CN.js',
					language: 'zh_CN',
					skin_url: 'static/tinymce/skins/ui/oxide',
					height: 430,
					plugins: 'axupimgs link lists image code table colorpicker textcolor wordcount contextmenu media',
					toolbar: [
						'axupimgs image bold italic underline strikethrough | fontsizeselect | forecolor backcolor ',
						'alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote',
						'undo redo | link unlink  code | removeformat media'
					],
					convert_urls: false,
					branding: false,
					media_live_embeds: true,
					images_upload_handler: function(blobInfo, succFun, failFun) {
						var fileObj = blobInfo.blob();
						uploadPlugin.file_upload(fileObj, function(){}, succFun, store.getters.getToken);
					},

					selector:''

				},
				defaultProps: {
					children: 'child',
					label: 'title',
					value: 'id',
				},
				editorOption: {
					modules: {
						toolbar: '#editorAb',
						imageResize: {
							displaySize: true
						},
					},
				},
				content: {},
				image_array: [],
				tinymceHtml: '请输入内容',
				randomId: '',
				inital_defaultValue: '',
				child_defaultValue: '',

			}
		},
		components: {
			Editor
		},
		computed: {
			editor: {
				get: function() {
					const self = this;
					return self.$refs.myTextEditor.quill;
				},
				set: function(newValue) {
					const self = this;
					self.$refs.myTextEditor.quill = newValue;
				}
			}

		},
		created() {
      const self = this;
			self.randomId = Math.ceil(Math.random() * 10000) + 'map';
			this.init.selector = '#' + self.randomId;
		},
		mounted() {

      if(!this.defaultValue&&this.defaultValue!=0){
        this.inital_defaultValue = this.defaultValue;
        this.child_defaultValue = this.defaultValue;
      };
			var url = document.location.toString();
			var baseUrl = url.split("#")[0];
			this.init.language_url = baseUrl + this.init.language_url;
			this.init.skin_url = baseUrl + this.init.skin_url;

		},

		methods: {


			onEditorFocus(editor) {
				const self = this;
				self.editor = editor //当content获取到焦点的时候就 存储editor
			},

			customButtonClick() {
				const self = this;
				var range
				if (self.editor.getSelection() != null) {
					range = self.editor.getSelection()
					self.length = range.index //content获取到焦点，计算光标所在位置，目的为了在该位置插入img
				} else {
					self.length = self.content.length //content没有获取到焦点时候 目的是为了在content末尾插入img
				}
				self.$el.querySelector('.custom-input').click(); //打开file 选择图片
			},


			async upload(e) {

				const self = this;
				let file = e.target.files[0];
				var obj = file.name.lastIndexOf(".");
				var ext = file.name.substr(obj + 1);
				let param = new FormData() // 创建form对象

				param.append('file', file, file.name) // 通过append向form对象添加数据
				param.append('token', store.getters.getToken);
				param.append('ext', ext);
				param.append('md5', 'md5');

				param.append('totalSize', file.size);
				param.append('start', 0);
				param.append('chunkSize', file.size);
				param.append('originName', file.name);
				// POST表单数据
				//param.append('chunk', '0') // 添加form表单中其他数据
				//console.log(param.get('file'))  FormData私有类对象，访问不到，可以通过get判断值是否传进去
				let config = {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				}
				//console.log(param.get('file'));
				var res = await self.$$api_uploadImg({
					data: param,
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				});
				if (res.solely_code == 100000) {

					self.contentImg = res.info.url; //获取到了图片的URL

					//判断文件类型渲染(H5 video标签只支持H264编码的MP4)
					var videoArray = ['mp4'];
					var url = res.info.url;

					var obj = url.lastIndexOf(".");
					var ext = url.substr(obj + 1);
					if (videoArray.indexOf(ext) != -1) {
						self.editor.insertEmbed(self.length, 'video', self.contentImg);
					} else {
						self.editor.insertEmbed(self.length, 'image', self.contentImg)
					};
					var jqObj = self.$el.querySelector('.custom-input');
					jqObj.value = "";

				}
			},



		},
    watch:{

      child_defaultValue(val) {
        const self = this;

        if(this.child_defaultValue.indexOf('data:image/png;base64,')>-1||this.child_defaultValue.indexOf('data:image/jpg;base64,')>-1){
          this.$message({message: '图片请上传保存，粘贴截图请删除，否则之后的数据不保存',type: 'warning'});
        }else{
          this.$emit('onChange', {field:this.field,value:this.child_defaultValue})
        }
      },

    },

	}
</script>
<style>
	.tox-tinymce-aux {
		z-index: 9999 !important
	}
</style>
